package com.aruba.attendance.home.view

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.aruba.attendance.R
import com.aruba.attendance.activity.NAV_SETTING_TIME
import com.aruba.attendance.extension.date.format
import com.aruba.attendance.home.viewmodel.HomeViewModel
import com.aruba.attendance.ui.dialog.PictureDialog
import com.aruba.attendance.ui.dialog.rememberPictureDialogState
import com.aruba.attendance.ui.widget.calendar.rememberSelectDateState
import com.aruba.attendance.ui.widget.datepicker.DatePickerDialog
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import java.util.*

/**
 * Created by aruba on 2023/3/10.
 */
/**
 * 导航-日历
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun NavHome(
    navController: NavHostController,
    homeViewModel: HomeViewModel,
    toStartPhoto: (((denial: Boolean) -> Unit) -> Unit)? = null,
) {
    val date = Calendar.getInstance()
    var selectYear by rememberSaveable { mutableStateOf(date.get(Calendar.YEAR)) }
    var selectMonth by rememberSaveable { mutableStateOf(date.get(Calendar.MONTH) + 1) }
    var selectDayOfMonth by rememberSaveable { mutableStateOf(date.get(Calendar.DAY_OF_MONTH)) }
    val initialSelectDate = rememberSelectDateState(selectDate = date.time.format())

    // 本地记录数据
    val selectDayRecordList by homeViewModel
        .findRecordByDate(selectYear, selectMonth, selectDayOfMonth)
        .collectAsState(initial = arrayListOf())

    val snackbarState by remember { mutableStateOf(SnackbarHostState()) }
    val scope = rememberCoroutineScope()

    // 照片弹框状态
    val pictureDialogState = rememberPictureDialogState()
    // 设置弹框
    val showSettingDialog = remember { mutableStateOf(false) }
    // 日期弹框
    val showDateDialog = remember { mutableStateOf(false) }
    // 日期选中
    val onDateSelected = { year: Int, month: Int, dayOfMonth: Int ->
        // 选择日期后，重新获取数据
        selectYear = year
        selectMonth = month
        selectDayOfMonth = dayOfMonth
    }

    HomeScaffold(
        toSetting = {
            showSettingDialog.value = !showSettingDialog.value
        },
        toStartPhoto = {
            toStartPhoto?.invoke { denial ->
                if (denial) {
                    scope.launch {
                        snackbarState.showSnackbar("摄像头未授权")
                    }
                }
            }
        },
        initialSelectDate = initialSelectDate,
        onDateSelected = onDateSelected,
        snackbarState = snackbarState,
        calendarContent = { scrollState ->
            Column {
                // 打卡记录列表
                LazyColumn(
                    state = scrollState,
                    contentPadding = PaddingValues(top = 7.dp, bottom = 7.dp),
                    verticalArrangement = Arrangement.spacedBy(5.dp)
                ) {
                    itemsIndexed(selectDayRecordList) { index, recordEntity ->
                        RecordListItem(
                            recordEntity = recordEntity,
                            modifier = Modifier.animateItemPlacement(),
                        ) {
                            // 显示弹框
                            pictureDialogState.show(recordEntity.photoPath)
                        }
                    }
                }
            }
        },
        content = {
            SettingDialog(
                show = showSettingDialog,
                items = stringArrayResource(id = R.array.setting_menu),
                selectCallback = { index ->
                    when (index) {
                        0 -> {//跳转至指定日期
                            showDateDialog.value = true
                        }
                        1 -> {//打卡时间设置
                            navController.navigate(NAV_SETTING_TIME) {
                                launchSingleTop = true
                            }
                        }
                        2 -> {//加班时长
                            scope.launch {
                                val findDurationFlowByDate = homeViewModel
                                    .findDurationFlowByDate(
                                        selectYear,
                                        selectMonth,
                                        selectDayOfMonth
                                    )
                                val findDurationSumFlow = homeViewModel.findDurationSumFlow()
                                findDurationFlowByDate.combine(
                                    findDurationSumFlow
                                ) { currentDayDuration, allDuration ->
                                    "当天加班时长(分钟):${
                                        (currentDayDuration ?: 0L) / (60 * 1000)
                                    }  累积时长(分钟):${(allDuration ?: 0L) / (60 * 1000)}"
                                }.collect { msg ->
                                    val result = snackbarState.showSnackbar(
                                        message = msg,
                                        duration = SnackbarDuration.Long,
                                        actionLabel = "确定"
                                    )

                                    when (result) {
                                        SnackbarResult.ActionPerformed -> {
                                            snackbarState.currentSnackbarData?.dismiss()
                                        }
                                        SnackbarResult.Dismissed -> {
                                        }
                                    }
                                }
                            }
                        }
                    }
                })
            PictureDialog(pictureDialogState)
            DatePickerDialog(showDateDialog) { date ->
                initialSelectDate.scrollToDate(date.format())
                onDateSelected(1900 + date.year, date.month + 1, date.date)
            }
        }
    )
}